package org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql;

import java.util.ArrayList;
import java.util.List;

import org.bambrikii.kbManager.kb2.managers.query4.ConditionSource;
import org.bambrikii.kbManager.kb2.managers.query4.ConditionType;
import org.bambrikii.kbManager.kb2.managers.query4.ICondition;
import org.bambrikii.kbManager.kb2.managers.query4.Or;
import org.bambrikii.kbManager.kb2.managers.query4.impl.builders.hql.q.HQLCriteria;

public class OrImpl extends Or<HQLCriteria> {
	public OrImpl(ConditionType type, ICondition<HQLCriteria>[] conditions) {
		super(type, conditions);
	}

	public HQLCriteria buildCriteria() {
		List<ConditionSource> aliases = new ArrayList<ConditionSource>();
		aliases.add(getFrom());

		StringBuilder sb = new StringBuilder();
		List<ICondition<HQLCriteria>> conds = getConditions();
		int n = conds.size();
		if (n > 0) {
			HQLCriteria crit = conds.get(0).buildCriteria();
			addCondition(crit, sb);
			aliases.addAll(crit.getFrom());
			for (int i = 1; i < n; i++) {
				crit = conds.get(i).buildCriteria();
				sb.append(" or ");
				addCondition(crit, sb);
				aliases.addAll(crit.getFrom());
			}
		}

		HQLCriteria crit = new HQLCriteria(aliases, "(\n" + sb.toString()
				+ ")\n");
		return crit;
	}

	private void addCondition(HQLCriteria from, StringBuilder sb) {
		sb.append(" (");
		sb.append(from.getCondition());
		sb.append(")\n ");
	}
}
